<template>
  <div>
    <div class="infotopclass">
      <span>商品信息列表</span>
      <div>
        <el-button type="primary" icon="el-icon-search" size="small" @click="checkstoreFn('hot')">查看热门商品</el-button>
        <el-button type="primary" icon="el-icon-search" size="small" @click="checkstoreFn('all')">查看所有商品</el-button>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addcategoryFn">添加商品信息</el-button>
      </div>
    </div>
      <!-- 添加商品信息的对话框 -->
    <el-dialog title="添加商品信息" :visible.sync="dialogstoreinfoVisible" fullscreen @close="resetDialog">
      <el-form :model="storeinfoForm" :rules="storeinfoFormRules" ref="storeinfoFormRef">
        <el-form-item label="商品名称" :label-width="formLabelWidth" prop="product_name">
          <el-input autocomplete="off" v-model="storeinfoForm.product_name"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" :label-width="formLabelWidth" class="addimg" prop="product_img">
          <el-checkbox-group v-model="storeinfoForm.product_img" v-show="false"></el-checkbox-group>
          <img src="../../../assets/images/addPicture.jpg" alt="" ref="imgRef">
          <input type="file" style="display:none" ref="iptRef" accept="image/*" @change="oncoverChangeFN">
          <br>
          <el-button type="text" @click="clickipt">添加图片</el-button>
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
          <el-input autocomplete="off" v-model="storeinfoForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品详情" :label-width="formLabelWidth" prop="detail">
          <el-input autocomplete="off" v-model="storeinfoForm.detail"></el-input>
        </el-form-item>
        <el-form-item label="库存" :label-width="formLabelWidth" prop="product_num">
          <el-input-number v-model="storeinfoForm.product_num" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item label="商品分类" :label-width="formLabelWidth" prop="category">
          <el-select  v-model="storeinfoForm.category" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.cate_name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogstoreinfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddstoreinfo">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
        :data="currentstoreinfodata"
        style="width: 100%">
        <el-table-column
        type="index"
        label="序号">
        </el-table-column>
        <el-table-column
        prop="product_name"
        label="商品名称"
        width="180">
        <template slot-scope="scope">
          <img src="../../../assets/hot.png" alt="" v-if="scope.row.hot == 1" class="hoticon">
          <span>{{ scope.row.product_name }}</span>
        </template>
        </el-table-column>
        <el-table-column
          prop="product_img"
          label="商品图片"
          width="180">
          <template slot-scope="scope">
            <img :src="scope.row.product_img" alt="" class="cover_img">
          </template>
        </el-table-column>
        <el-table-column
        prop="price"
        label="商品价格">
        <template slot-scope="scope">
            <span>￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
        label="商品详情">
        <template slot-scope="scope">
          <p class="store_detail">
            {{ scope.row.detail }}
          </p>
        </template>
        </el-table-column>
        <el-table-column
        prop="product_num"
        label="库存">
        </el-table-column>
        <el-table-column
        prop="category"
        label="商品分类">
        </el-table-column>
        <el-table-column
        label="发布者">
        <template slot-scope='{row}'>
          <span v-if="row.Author">{{ row.Author }}</span>
          <span v-else>易儿宝商户</span>
        </template>
        </el-table-column>
        <el-table-column
        prop="hot"
        label="热门推荐">
        <template slot-scope="scope">
          &nbsp;
          <el-button size="mini" type="success" icon="el-icon-check" circle v-if="scope.row.hot == 1" @click="setHot(scope.row)"></el-button>
          <el-button size="mini" type="danger" icon="el-icon-close" circle v-else @click="setHot(scope.row)"></el-button>
        </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="150">
            <template slot-scope="scope">
                <el-button
                size="mini"
                @click="handleEdit(scope.row)"><i class="el-icon-edit"></i></el-button>
                <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"><i class="el-icon-delete"></i></el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :current-page="currentPage"
      :total="storeinfodata.length"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
import { getstoreinfoAPI, addstoreinfoAPI, deletstoreinfoAPI, updatestoreinfoAPI, setHotAPI, getHotstoreAPI } from '@/api'
import imgUrl from '../../../assets/images/addPicture.jpg'
export default {
  name: 'admin-storeinfo',
  data () {
    return {
      // 全部商品数据存储
      storeinfodata: [],
      // 对话框开关
      dialogstoreinfoVisible: false,
      formLabelWidth: '80px',
      chosecategory: {
        category: ''
      },
      storeinfoForm: {
        product_name: '',
        product_img: '',
        price: '',
        detail: '',
        product_num: '',
        category: ''
      },
      searchForm: {
        category: ''
      },
      // 获取的商品信息
      categoryList: [],
      // 表单验证规则
      storeinfoFormRules: {
        product_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        product_img: [
          { required: true, message: '请上传商品图片', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '请输入商品详情', trigger: 'blur' }
        ],
        product_num: [
          { required: true, message: '请输入商品库存', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        comment: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' }
        ]
      },
      // 判断用户点击的是添加 还是 编辑 false为编辑 true 为添加
      isEdit: true,
      // 保存商品id - 编辑商品信息时传入
      storeID: '',
      currentPage: 1, // 当前页码
      pageSize: 10 // 每页显示数量
    }
  },
  computed: {
    totalPages () {
      return Math.ceil(this.storeinfodata.length / this.pageSize) // 总页数
    },
    currentstoreinfodata () {
      const startIndex = (this.currentPage - 1) * this.pageSize
      const endIndex = startIndex + this.pageSize
      return this.storeinfodata.slice(startIndex, endIndex)
    }
  },
  mounted () {
    this.getstoreinfoList()
    this.categoryList = this.$store.state.category
  },
  methods: {
    // 获取全部商品信息
    async getstoreinfoList () {
      const { data } = await getstoreinfoAPI()
      if (data.status !== 0) return this.$message.error(data.message)
      this.storeinfodata = data.data
    },
    // 获取热门商品信息 / 全部商品
    async gethotstoreList () {
      const { data } = await getHotstoreAPI()
      if (data.status !== 0) return this.$message.error(data.message)
      this.storeinfodata = data.data
      this.$message.success(data.message)
    },
    // 点击按钮 查看热门商品
    checkstoreFn (str) {
      if (str === 'hot') {
        this.gethotstoreList()
      } else {
        this.getstoreinfoList()
        this.$message.success('全部商品获取成功')
      }
    },
    // 添加商品信息按钮 - 打开对话框
    addcategoryFn () {
      this.isEdit = true
      this.dialogstoreinfoVisible = true
    },
    clickipt () {
      this.$refs.iptRef.click()
    },
    oncoverChangeFN (e) {
      const file = e.target.files
      if (file.length === 0) {
        this.storeinfoForm.product_img = null
        this.$refs.imgRef.setAttribute('src', imgUrl)
      } else {
        const fr = new FileReader()
        fr.readAsDataURL(file[0])
        fr.onload = (e) => {
          this.$refs.imgRef.setAttribute('src', e.target.result)
          this.storeinfoForm.product_img = e.target.result
        }
      }
    },
    // 设置为热门
    async setHot (item) {
      if (item.hot === 1) {
        const { data } = await setHotAPI(0, item.id)
        if (data.status !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
      } else {
        const { data } = await setHotAPI(1, item.id)
        if (data.status !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
      }
      this.getstoreinfoList()
    },
    // 编辑
    handleEdit (item) {
      this.storeID = item.id
      // 将isEdit 修改为false - 表示用户点击编辑
      this.isEdit = false
      this.dialogstoreinfoVisible = true
      this.$nextTick(() => {
        this.storeinfoForm.product_name = item.product_name
        this.storeinfoForm.product_img = item.product_img
        this.storeinfoForm.price = item.price
        this.storeinfoForm.detail = item.detail
        this.storeinfoForm.product_num = item.product_num
        this.storeinfoForm.category = item.category
        this.storeinfoForm.comment = item.comment
        this.$refs.imgRef.setAttribute('src', item.product_img)
      })
    },
    // 确定添加 / 修改按钮 -当isEdit=true时为新增 当isEdit=false时为编辑
    confirmAddstoreinfo () {
      this.$refs.storeinfoFormRef.validate(async valid => {
        if (valid) {
          if (this.isEdit) {
            const { data } = await addstoreinfoAPI(this.storeinfoForm)
            if (data.status === 1) return this.$message.error(data.message)
            this.$message.success(data.message)
          } else {
            this.storeinfoForm.id = this.storeID
            const { data } = await updatestoreinfoAPI(this.storeinfoForm)
            if (data.status === 1) return this.$message.error(data.message)
            this.$message.success(data.message)
          }
          this.dialogstoreinfoVisible = false
          this.getstoreinfoList()
        } else {
          return false
        }
      })
    },
    // 关闭对话框 - 重置表单
    resetDialog () {
      this.$refs.storeinfoFormRef.resetFields()
      this.storeinfoForm.product_img = null
      this.$refs.imgRef.setAttribute('src', imgUrl)
    },
    // 删除
    async handleDelete (item) {
      const { data } = await deletstoreinfoAPI(item.id)
      if (data.status !== 0) return this.$message.error(data.message)
      this.$message.success(data.message)
      this.getstoreinfoList()
    },
    handleCurrentChange (newPage) {
      this.currentPage = newPage
    }
  }
}
</script>

<style scoped>
  * {
    font-size: 10px;
  }
  .infotopclass{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  /* 添加图片的图片大小 */
  .addimg img {
    width: 150px;
    height: 130px;
  }
  /* 表格图片大小 */
  .cover_img {
    width: 50px;
    height: 50px;
  }
  .el-table {
    border-radius: 8px;
  }
  .hoticon {
    width: 18px;
    height: 18px;
    vertical-align:middle;
    margin-right: 2px;
  }
  .el-button {
    border-radius: 8px;
  }
  .store_detail {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    font-size: 12px;
    cursor:pointer;
  }
</style>
